import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
    meta: { guestOnly: true }
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/:catchAll(.*)',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 如果目标路由需要授权，且没有认证信息，重定向到登录页面
    next({ name: 'login' })
  } else if (to.meta.guestOnly && isAuthenticated) {
    // 如果目标路由只允许未认证用户访问，且用户已认证，重定向到主页
    next({ name: 'home' })
  } else {
    // 允许访问目标路由
    next()
  }
})

export default router
